<template>
	<view class="flex index-view">
		<image src="../../static/images/index/login.png" class="login-img"></image>
		<u-button type="primary" class="reg-login" open-type="getUserInfo" @getuserinfo="getUserInfo">微信一键登陆</u-button>
	</view>
</template>

<script>
export default{
	data(){
		return{
		  code: "",
		}
	},
	mounted() {
	
	},
	onLoad: function() {
		uni.login({
			provider: 'weixin',
			success: (res) => {
				if (res.errMsg == "login:ok") {
					this.code = res.code;
				}
			},
			fail: (res) => {
				
			}
		})
	},
	methods:{
		getUserInfo(e) {
			//初始化加载，先判断用户登录状态
				if (wx.getStorageSync('token')) {
					wx.switchTab({
						url: 'pages/index/index'
				    })
				}
				else{
					let that = this
					var p = this.getSetting()
					p.then(function(isAuth) {
						if (isAuth) {
							let eData = JSON.parse(e.detail.rawData);   //eData  包括//微信头像//微信名称 还有加密的数据.
							uni.showToast({
								title: "正在登录",
								icon: "none"
							})
						
							that.$login(that.code, eData).then((res) => {
								uni.setStorage({
									key:"token",
									data:res.data.data.token,
								})
								uni.switchTab({
									url: '../index/index'
								})
								
							})
						}
					})
					
			}
		},
		
		//获取用户的当前设置
		getSetting() {
			return new Promise(function(resolve, reject) {
				uni.getSetting({
					success: function(res) {
						if (res.authSetting['scope.userInfo']) {
							resolve(true);
						} else {
							resolve(false);
						}
					}
				})
			}).catch((e) => {
			
			});
		},
		
	},
}
</script>

<style>
.index-view{
	flex-direction: column;
	justify-content: center;
}
.login-img{
	width:96vw;
	margin:10rpx auto;
}
.reg-login{
	width:300rpx;
	margin:100rpx auto;
}
</style>
